package com.jacky.iot.handler;

import com.jacky.iot.proto.TaskProto;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class ClientProtobufHandler extends ChannelInboundHandlerAdapter {

    private static final Logger LOG = LoggerFactory.getLogger(ClientProtobufHandler.class);
    private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    private final AtomicInteger atomicInteger = new AtomicInteger(1);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        executor.scheduleAtFixedRate(() -> {
            int packType = new Random().nextInt(3);
            switch (TaskProto.PackType.forNumber(packType)) {
                case LOGIN:
                    TaskProto.LoginPack lp = TaskProto.LoginPack.newBuilder().setUsername("李四[" + atomicInteger.getAndIncrement() + "]")
                            .setPassword("13525" + atomicInteger.get()).build();
                    ctx.writeAndFlush(TaskProto.TaskProtocol.newBuilder().setPackType(TaskProto.PackType.LOGIN).setLoginPack(lp));
                    break;
                case CREATE_TASK:
                    TaskProto.CreateTaskPack ctp = TaskProto.CreateTaskPack.newBuilder().setTaskId("100" + atomicInteger.get())
                            .setTaskName("任务编号:" + atomicInteger.get())
                            .setCreateTime(System.currentTimeMillis()).build();
                    ctx.writeAndFlush(TaskProto.TaskProtocol.newBuilder().setPackType(TaskProto.PackType.CREATE_TASK).setCreateTaskPack(ctp));
                    break;
                case DELETE_TASK:
                    TaskProto.DeleteTaskPack dtp = TaskProto.DeleteTaskPack.newBuilder()
                            .addTaskId("1001").addTaskId("100" + (atomicInteger.get() - 1)).build();
                    ctx.writeAndFlush(TaskProto.TaskProtocol.newBuilder().setPackType(TaskProto.PackType.DELETE_TASK).setDeleteTaskPack(dtp));
                    break;
                default:
                    LOG.error("产生一个未知的包类型:{}", packType);
                    break;
            }
        }, 0, 1, TimeUnit.SECONDS);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        LOG.error("客户端发生异常:", cause);
    }
}
